package com.qian.fmall.order.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.qian.fmall.order.orderInterface.OrderService;
import com.qian.fmall.order.wconfig.WenSocketServer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wPay")
public class WPayNotify {
    @Resource
    private OrderService orderService;
    @RequestMapping("/success")
    public String wNotify(HttpServletRequest request) throws Exception {
        ServletInputStream is = request.getInputStream();
        byte[] b=new byte[1024];int len=0;
        String str="";
        while((len=(is.read(b)))!=-1)
        {
            str+=new String(b,0,len);
        }
        Map<String, String> reqMap = WXPayUtil.xmlToMap(str);
        while(reqMap!=null&&"success".equalsIgnoreCase(reqMap.get("result_code"))){
            String orderId = reqMap.get("out_trade_no");
            int i = orderService.updateOrderStatus(orderId, "2");
            System.out.println("--orderId:"+orderId);
            WenSocketServer.sendMessage(orderId,"1");
            //3.响应微信支付平台
            if(i>0){
                HashMap<String,String> resp = new HashMap<>();
                resp.put("return_code","success");
                resp.put("return_msg","OK");
                resp.put("appid",reqMap.get("appid"));
                resp.put("result_code","success");
                return WXPayUtil.mapToXml(resp);
            }
        }
        return null;
    }
}
